const baseUrl = 'http://8.138.211.226:8111/api'

// 创建带 Token 的请求头
export const createAuthHeader = (contentType = "application/json") => {
  const header = {
    "Content-Type": contentType,
  };

  const accessToken = uni.getStorageSync("accessToken");
  if (accessToken) {
    header["Authentication"] = `Bearer ${accessToken}`;
  }
  return header;
};

// 检查Token是否需要刷新
export const checkTokenExpirationStatus = (type = "access") => {
  const token = uni.getStorageSync(type === "access" ? "accessToken" : "refreshToken");
  const expiresIn = Number(uni.getStorageSync(`${type}ExpiresIn`));
  const currentTime = Date.now();

  // 提前30秒过期
  return token && expiresIn && currentTime >= (expiresIn - 30000);
};

// 清除登录相关信息
export const clearLoginInfo = () => {
  uni.removeStorageSync('accessToken')
  uni.removeStorageSync('refreshToken')
  uni.removeStorageSync('accessExpiresIn')
  uni.removeStorageSync('refreshExpiresIn')
  uni.removeStorageSync('userInfo')
  uni.removeStorageSync('openIdMini')
  uni.removeStorageSync('userId')
};

// 刷新token
export const refreshAndGetNewAccessToken = async () => {
  const accessToken = uni.getStorageSync('accessToken')
  const refreshToken = uni.getStorageSync('refreshToken')

  if (!refreshToken) {
    throw new Error('没有刷新令牌，无法刷新访问令牌')
  }

  try {
    const res = await uni.request({
      url: `${baseUrl}/user/refresh`,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authentication': `Bearer ${accessToken}`
      },
      data: {
        refreshToken: refreshToken
      }
    });

    if (res.data.code === 0) {
      const responseData = res.data.data || {}

      if (!responseData.accessToken || !responseData.refreshToken) {
        throw new Error('刷新Token响应数据不完整')
      }

      // 更新存储的token信息
      uni.setStorageSync('accessToken', responseData.accessToken)
      uni.setStorageSync('refreshToken', responseData.refreshToken)

      if (responseData.accessExpiresIn) {
        uni.setStorageSync('accessExpiresIn', responseData.accessExpiresIn.toString())
      }

      return responseData.accessToken
    } else {
      throw new Error(res.data.message || 'token已过期，请重新登录')
    }
  } catch (error) {
    clearLoginInfo()
    throw error
  }
};

export const checkAndRefreshToken = async () => {
  // 检查accessToken是否需要刷新
  if (checkTokenExpirationStatus("access")) {
    try {
      // 尝试刷新Token
      await refreshAndGetNewAccessToken();
    } catch (error) {
      // 刷新失败处理
      clearLoginInfo();
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login/login' });
      }, 1000);
      throw error;
    }
  }
};

// 请求拦截器处理函数
const requestInterceptor = async (config) => {
  // 检查是否需要携带 Token（排除登录相关接口）
  const isAuthRequired = !config.url?.includes("/user/qr") &&
      !config.url?.includes("/user/login")

  if (isAuthRequired) {
    const accessToken = uni.getStorageSync("accessToken");

    // 检查accessToken是否需要刷新
    if (accessToken && checkTokenExpirationStatus("access")) {
      try {
        // 尝试刷新Token
        await refreshAndGetNewAccessToken();
      } catch (error) {
        // 刷新失败：清除Token并跳转到登录页
        clearLoginInfo();
        uni.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none'
        });

        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login/login' });
        }, 1000);

        throw new Error("Token刷新失败，已退出登录");
      }
    }

    // 统一使用createAuthHeader创建请求头（自动获取最新token）
    const contentType = config.header?.["content-type"] || "application/json";
    const authHeader = createAuthHeader(contentType);
    config.header = { ...config.header, ...authHeader };
  }

  // 处理URL
  if (!config.url.startsWith('http')) {
    config.url = `${baseUrl}/${config.url}`;
  }

  return config;
};

// 响应拦截器处理函数
const responseInterceptor = (response) => {
  // 处理HTTP状态码错误（如401未授权）
  if (response.statusCode === 401) {
    clearLoginInfo();
    uni.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' });
    }, 1000);
    throw new Error("登录已过期，请重新登录");
  }

  // 处理后端业务状态码错误（如果需要）
  // if (response.data && response.data.code !== 0) {

  //   throw new Error(response.data.message || '操作失败');
  // }

  return response.data;
};

// 导出请求方法
export default async (config) => {
  try {
    // 应用请求拦截器
    const processedConfig = await requestInterceptor({ ...config });

    // 发起请求 - uni.request返回的是数组 [error, success]
    return new Promise((resolve, reject) => {
      uni.request({
        ...processedConfig,
        success: (res) => {
          try {
            // 应用响应拦截器
            const processedResponse = responseInterceptor(res);
            resolve(processedResponse);
          } catch (error) {
            reject(error);
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  } catch (error) {
    return Promise.reject(error);
  }
};